const fs = require('fs')
const path = require('path')
const readline = require('readline')

class BadWords {
  constructor () {
    this.data = []
    const files = fs.readdirSync(path.resolve(__dirname, '../libs/'))
    files.forEach(file => {
      if (path.extname(file) === '.txt') {
        const rl = readline.createInterface({
          input: fs.createReadStream(path.resolve(__dirname, '../libs/', file))
        })
        rl.on('line', line => {
          if (line) {
            if (line.substring(line.length - 1) === ',') {
              line = line.substring(0, line.length - 1)
            }
            this.data.push(line)
          }
        })
      }
    })
  }

  static get instance () {
    if (!BadWords._instance) {
      BadWords._instance = new BadWords()
    }
    return BadWords._instance
  }

  filter (content) {
    let result = content

    // 匹配过滤词并用*替换
    this.data.forEach(keyword => {
      if (result.toUpperCase().includes(keyword.toUpperCase())) {
        const asterisks = []
        for (let i = 0; i < keyword.length; i++) {
          asterisks.push('*')
        }
        result = result.replace(new RegExp(keyword, 'gi'), asterisks.join(''))
      }
    })

    return result
  }
}

BadWords._instance = null

module.exports = BadWords
